package service

import (
	"daily-blog/dao"
	"daily-blog/global"
	"daily-blog/model"
	"daily-blog/pkg"
)

func CreateComment(comment *model.Comment) bool {
	comment.CommentId = pkg.GenUUID()
	if err := dao.CreateComment(comment); err != nil {
		global.GVA_LOG.Error(err.Error())
		return false
	}
	return true
}
func DeleteComment(postId, commentId string) bool {
	if err := dao.DeleteComment(postId, commentId); err != nil {
		global.GVA_LOG.Error(err.Error())
		return false
	}
	return true
}
func GetCommentList(postId string) ([]model.CommentInfo, bool) {
	comments, err := dao.GetCommentListByPostId(postId)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, false
	}
	return comments, true
}

// GetAllPostAllCommentList 获取所有的文章的所有评论
func GetAllPostAllCommentList() ([]*model.PostCommentInfo, bool) {
	commentList, err := dao.GetCommentList()
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, false
	}
	// 给客户端返回的commentList
	var postCommentList []*model.PostCommentInfo
	for i, comment := range commentList {
		var commentM *model.CommentMain
		if comment.CommentId != "" {
			commentM = new(model.CommentMain)
			commentM.CommentId = comment.CommentId
			commentM.Author = comment.Author
			commentM.Content = comment.Content
			commentM.Email = comment.Email
		}
		if i == 0 { // 第一个post，直接创建对应的评论结构体
			postCommentList = append(postCommentList, &model.PostCommentInfo{PostId: comment.PostId, Title: comment.Title, CommentList: []*model.CommentMain{commentM}})
			continue
		}
		// 不是第一个post的时候，需要看前一个的post_id 和 当前的这个post_id是否一致如果一致把当前的comment直接放到post的中，如果不一致，就创建新的post
		if comment.PostId == postCommentList[len(postCommentList)-1].PostId {
			onePostCommentList := postCommentList[len(postCommentList)-1].CommentList
			onePostCommentList = append(onePostCommentList, commentM)
			postCommentList[len(postCommentList)-1].CommentList = onePostCommentList
		} else {
			postCommentList = append(postCommentList, &model.PostCommentInfo{PostId: comment.PostId, Title: comment.Title, CommentList: []*model.CommentMain{commentM}})
		}
	}
	return postCommentList, true
}
